import { PlusOutlined, ExclamationCircleOutlined, EllipsisOutlined } from '@ant-design/icons';
import { Button, Menu, Modal, Tag, TreeSelect } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import TableForm from './components/TableForm';
import HeaderDropdown from '@/components/HeaderDropdown/index';
import { services } from '@/network/api';
import utils from '@/utils/index';

type formState = {
  visible?: boolean;
  id?: any;
};

type UserCol = {
  id: number;
  name: string;
  email: string;
  isLogin: number;
  phone: number;
  adress: string;
  createDate: string;
  birthDate: string;
  sex: string;
  access: any;
  job: any;
  department: any;
  province: any;
  city: any;
};

const { confirm } = Modal;

const TableList: React.FC = (props: any) => {
  const { route } = props;
  const [formState, setFormState] = useState<formState>({
    visible: false,
    id: null,
  });
  const [selectedRows, setSelectedRows] = useState<UserCol[]>([]);
  const actionRef = useRef<ActionType>();
  const [columns, setColumns]: [ProColumns<UserCol>[], any] = useState([
    {
      title: '用户id',
      dataIndex: 'id',
      sorter: true,
    },
    {
      title: '用户名称',
      dataIndex: 'name',
      sorter: true,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      sorter: true,
    },
    {
      title: '手机',
      dataIndex: 'phone',
      sorter: true,
    },
    {
      title: '省市',
      dataIndex: 'province_city',
      hideInSearch: true,
      render: (_, record) => {
        return `${record?.province?.name}/${record?.city?.name}`;
      },
    },
    {
      title: '地址',
      dataIndex: 'adress',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '角色',
      dataIndex: 'access',
      hideInSearch: true,
      render: (_, record) => {
        return record?.access?.map((item: any) => {
          return <Tag color="blue">{item?.name}</Tag>;
        });
      },
    },
    {
      title: '角色',
      dataIndex: 'accessIds',
      valueType: 'select',
      hideInTable: true,
      fieldProps: {
        mode: 'multiple',
      },
      request: async (params) => {
        let res = await services.getAccessList({ noPagination: true, noMsg: true, state: 1 });
        return res?.data?.map((item: any) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
      },
    },
    {
      title: '岗位',
      dataIndex: 'job',
      hideInSearch: true,
      render: (_, record) => {
        return record?.job?.map((item: any) => {
          return <Tag color="blue">{item?.name}</Tag>;
        });
      },
    },
    {
      title: '岗位',
      dataIndex: 'jobIds',
      valueType: 'select',
      hideInTable: true,
      fieldProps: {
        mode: 'multiple',
      },
      request: async (params) => {
        let res = await services.getJobList({ noPagination: true, noMsg: true });
        return res?.data?.map((item: any) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
      },
    },
    {
      title: '部门',
      dataIndex: 'department',
      hideInSearch: true,
      render: (_, record) => {
        return !!record?.department?.name && <Tag color="blue">{record?.department?.name}</Tag>;
      },
    },
    {
      title: '部门',
      dataIndex: 'departmentIds',
      valueType: 'select',
      hideInTable: true,
      fieldProps: {
        mode: 'multiple',
      },
      renderFormItem: () => {
        return (
          <TreeSelect treeData={departmentList} treeCheckable={true} placeholder="请选择部门" />
        );
      },
    },
    {
      title: '性别',
      dataIndex: 'sex',
      sorter: true,
      valueEnum: {
        男: {
          text: '男',
        },
        女: {
          text: '女',
        },
      },
    },
    {
      title: '是否在线',
      dataIndex: 'isLogin',
      valueEnum: {
        0: {
          text: '离线',
          status: 'Default',
        },
        1: {
          text: '在线',
          status: 'Success',
        },
      },
      sorter: true,
    },
    {
      title: '出生日期',
      dataIndex: 'birthDate',
      valueType: 'date',
      sorter: true,
      hideInSearch: true,
      render: (_, record) => {
        return record.birthDate ? record.birthDate : '-';
      },
    },
    {
      title: '出生日期范围',
      dataIndex: 'birthDateRange',
      valueType: 'dateRange',
      hideInTable: true,
    },
    {
      title: '创建日期',
      dataIndex: 'createDate',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '创建日期范围',
      dataIndex: 'createDateRange',
      valueType: 'dateTimeRange',
      hideInTable: true,
    },
    {
      title: '操作',
      fixed: 'right',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        route.checkBtn('edit') && (
          <a
            onClick={() => {
              setFormState({ ...formState, visible: true, id: record.id });
            }}
          >
            修改
          </a>
        ),
        route.checkBtn('delete') && (
          <a
            onClick={() => {
              confirm({
                title: '确认删除用户?',
                icon: <ExclamationCircleOutlined />,
                onOk() {
                  const delUserList = async () => {
                    await services.delUserList({ idList: [record.id] });
                    setTimeout(() => {
                      actionRef?.current?.reload();
                    }, 300);
                  };
                  delUserList();
                },
              });
            }}
          >
            删除
          </a>
        ),
        <HeaderDropdown
          overlay={
            <Menu selectedKeys={[]}>
              {/* {!!record.state && (
                <Menu.Item
                  onClick={() => {
                    const saveAccess = async () => {
                      await services.saveAccess({ state: 0, id: record.id });
                      setTimeout(() => {
                        actionRef?.current?.reload();
                      }, 300);
                    };
                    saveAccess();
                  }}
                >
                  停用
                </Menu.Item>
              )}
              {!record.state && (
                <Menu.Item
                  onClick={() => {
                    const saveAccess = async () => {
                      await services.saveAccess({ state: 1, id: record.id });
                      setTimeout(() => {
                        actionRef?.current?.reload();
                      }, 300);
                    };
                    saveAccess();
                  }}
                >
                  启用
                </Menu.Item>
              )} */}
            </Menu>
          }
        >
          <a>
            <EllipsisOutlined />
          </a>
        </HeaderDropdown>,
      ],
    },
  ]);

  //获取字段信息
  useEffect(() => {
    const getFieldList = async () => {
      const res = await services.getFieldList({
        noPagination: true,
        noMsg: true,
        noThrottle: true,
        isDefault: 0,
        isEnable: 1,
      });
      let customCols = [];
      customCols = res?.data?.map((item: any) => {
        return utils.constant.FORM_TYPE_LIST.toCols(item);
      });
      customCols = customCols?.filter((item: any) => {
        return !!item;
      });
      console.log(customCols);

      setColumns([...columns, ...customCols]);
    };
    getFieldList();
  }, []);

  const delAccessList = () => {
    confirm({
      title: '确认删除用户?',
      icon: <ExclamationCircleOutlined />,
      onOk() {
        const delAccessList = async () => {
          await services.delUserList({
            idList: selectedRows.map((item) => {
              return item.id;
            }),
          });
          setTimeout(() => {
            actionRef?.current?.clearSelected?.();
            actionRef?.current?.reload();
          }, 300);
        };
        delAccessList();
      },
    });
  };

  const [departmentList, setDepartmentList] = useState([]);
  //获取部门树
  useEffect(() => {
    const getDepartmentTree = async () => {
      const res = await services.getDepartmentTreeList({ noMsg: true, noThrottle: true });
      let data = utils.obj.treeSelectFormData(res?.data, {
        title: 'name',
        value: 'id',
        children: 'children',
      });
      setDepartmentList(data || []);
    };
    getDepartmentTree();
  }, []);

  return (
    <PageContainer>
      <ProTable
        headerTitle="用户管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolbar={{}}
        columnsState={{
          persistenceType: 'localStorage',
          persistenceKey: 'userTableColSet',
        }}
        toolBarRender={() => [
          route.checkBtn('add') && (
            <Button
              type="primary"
              onClick={() => {
                setFormState({ ...formState, visible: true, id: null });
              }}
            >
              <PlusOutlined /> 新建
            </Button>
          ),
          route.checkBtn('delete') && (
            <Button type="primary" disabled={!selectedRows?.length} danger onClick={delAccessList}>
              <PlusOutlined /> 批量删除
            </Button>
          ),
        ]}
        request={async (param, orderParam, ...arg) => {
          let res = await services.getUserList({
            ...param,
            orderParam,
            noMsg: true,
            noThrottle: true,
          });
          //自定义字段解析
          res?.data?.map((item: any) => {
            item?.custom?.map((_item: any) => {
              const [_noUse, _fieldId, fieldType] = _item.field.split('_');
              item[_item.field] = _item.value;
            });
          });
          return res;
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      <TableForm
        {...formState}
        onVisibleChange={(visible) => {
          setFormState({ ...formState, visible });
        }}
        _onFinish={() => {
          setFormState({ ...formState, visible: false });
          setTimeout(() => {
            actionRef?.current?.reload();
          }, 300);
        }}
      />
    </PageContainer>
  );
};

export default TableList;
